import { protectedProcedure, router } from '@/server/trpc-middlewares/trpc';
import { db } from '../db/db';
import { apiKeys, storageConfiguration } from '../db/schema';
import { desc } from 'drizzle-orm';
import { z } from 'zod';
import { v4 as uuid } from 'uuid';

export const apiKeysRouter = router({
  listApiKeys: protectedProcedure
    .input(z.object({ appId: z.string() }))
    .query(async ({ ctx, input }) => {
      return db.query.apiKeys.findMany({
        where: (apiKeys, { eq, and, isNull }) =>
          and(eq(apiKeys.appId, input.appId), isNull(apiKeys.deletedAt)),
        orderBy: [desc(apiKeys.createdAt)],
      });
    }),

  createApiKey: protectedProcedure
    .input(
      z.object({
        name: z.string().min(3).max(50),
        appId: z.string().uuid(),
      })
    )
    .mutation(async ({ ctx, input }) => {
      const { name, appId } = input;

      const result = await db
        .insert(apiKeys)
        .values({
          name,
          appId,
          key: uuid(),
        })
        .returning();

      return result[0];
    }),
});
